<template>
  <div class="page">
    <global-header title="赔率限额" @back="$router.back()">
      <template #right>
        <div
          class="absolute flex gap-[6.5px] items-center pr-[15px]"
          @click="gamesActionSelect?.handleShow()"
        >
          <span class="text-[14px] text-[#333333]">{{ currentData?.Name }}</span>
          <van-icon name="arrow-down" color="#111111" class="!text-[12px]"></van-icon>
        </div>
      </template>
    </global-header>
    <div class="w-[0] absolute left-[-10px]">
      <ActionSelect
        ref="gamesActionSelect"
        v-model:val="activeGameIndex"
        title="全部游戏"
        :columns="gamesActions"
      />
    </div>
    <main class="page-main" style="--van-collapse-item-content-padding: 0">
      <van-collapse v-model="collapse">
        <van-collapse-item
          v-for="(item, index) of state.list"
          :key="index"
          :title="`${item.Cat2}-${item.Cat3}`"
          :name="index"
        >
          <div
            class="relative w-full p-[15px] bg-[#F2F4FB] flex text-[14px] box-border items-center"
          >
            <span class="text-[#000721] w-[140px]">赔率：</span>
            <van-field
              class="flex-1"
              :border="false"
              style="padding: 0; background-color: transparent"
              type="number"
              v-model="item.Odds"
            />
            <span class="flex-1 text-right text-[12px] ml-[5px]">&lt;= {{ item.MaxOdds }}</span>
            <div class="absolute bottom-0 h-[1px] w-full bg-[#E4E4E4]"></div>
          </div>

          <div
            class="relative w-full p-[15px] bg-[#F2F4FB] flex text-[14px] box-border items-center"
          >
            <span class="text-[#000721] w-[140px]">个人单注最低限额：</span>
            <van-field
              class="flex-1"
              :border="false"
              style="padding: 0; background-color: transparent"
              type="number"
              :min="item.MinPersonl"
              :max="item.MaxMaxPreBet"
              v-model="item.RoomSingleMinLimit"
            />
            <span class="flex-1 text-right text-[12px] ml-[5px]">&gt;= {{ item.MinPersonl }}</span>
            <div class="absolute bottom-0 h-[1px] w-full bg-[#E4E4E4]"></div>
          </div>

          <div
            class="relative w-full p-[15px] bg-[#F2F4FB] flex text-[14px] box-border items-center"
          >
            <span class="text-[#000721] w-[140px]">个人单注最高限额：</span>
            <van-field
              class="flex-1"
              :border="false"
              style="padding: 0; background-color: transparent"
              type="number"
              :min="0"
              :max="item.MaxMaxPreBet"
              v-model="item.RoomSingleMaxLimit"
            />
            <span class="flex-1 text-right text-[12px] ml-[5px]"
              >&lt;= {{ item.MaxMaxPreBet }}</span
            >
            <div class="absolute bottom-0 h-[1px] w-full bg-[#E4E4E4]"></div>
          </div>

          <div
            class="relative w-full p-[15px] bg-[#F2F4FB] flex text-[14px] box-border items-center"
          >
            <span class="text-[#000721] w-[140px]">个人单期最高限额：</span>
            <van-field
              class="flex-1"
              :border="false"
              style="padding: 0; background-color: transparent"
              type="number"
              :min="0"
              :max="item.MaxMaxSingleBitch"
              v-model="item.MaxLimitPersonBet"
            />
            <span class="flex-1 text-right text-[12px] ml-[5px]"
              >&lt;= {{ item.MaxMaxSingleBitch }}</span
            >
            <div class="absolute bottom-0 h-[1px] w-full bg-[#E4E4E4]"></div>
          </div>

          <div
            class="relative w-full p-[15px] bg-[#F2F4FB] flex text-[14px] box-border items-center"
          >
            <span class="text-[#000721] w-[140px]">单期总限额：</span>
            <van-field
              class="flex-1"
              :border="false"
              style="padding: 0; background-color: transparent"
              type="number"
              :min="0"
              :max="item.MaxMaxBitch"
              v-model="item.RoomAllLimit"
            />
            <span class="flex-1 text-right text-[12px] ml-[5px]">&lt;= {{ item.MaxMaxBitch }}</span>
          </div>
        </van-collapse-item>
      </van-collapse>
    </main>
    <div class="p-[15px] bg-[#FFFFFF]">
      <div class="flex gap-[10px]">
        <van-button
          @click="handleSaveAll(true)"
          class="!flex-1 !bg-[#CDD9EE] !text-[#3976CC] rounded-[5px]"
          block
        >
          一键设置同类型游戏
        </van-button>
        <van-button
          @click="handleSaveAll(false)"
          class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]"
          block
        >
          保存设置
        </van-button>
      </div>
    </div>
  </div>
</template>
<route>
  {
    name: "admin-odds",
    meta: {
      pageIndex: 3,
    }
  }
</route>
<script setup lang="ts">
import { useGameStore } from "@/store/modules/game";
import { cloneDeep, isEqual } from "lodash-es";

import { storeToRefs } from "pinia";
import { reqGameOddsEdit, reqGameOddsShow } from "@/api/odds";
import { toast } from "@/utils/toast";
import { usePremsStore } from "@/store/modules/prems";

interface State {
  loading: boolean;
  msgGameInfoId: number;
  list: OddsSettingItem[];
  defaultList: OddsSettingItem[];
  odds: any;
  min: any;
  minLimit: number;
  max: number | null;
  maxLimit: number;
  persionMax: number | null;
  persionMaxLimit: number;
  all: number | null;
  allLimit: number;
}

const premsStore = usePremsStore();
const state = reactive<State>({
  loading: false,
  msgGameInfoId: 0,
  list: [],
  defaultList: [],
  odds: <number | null>null,
  min: <number | null>null,
  minLimit: 0,
  max: <number | null>null,
  maxLimit: 0,
  persionMax: <number | null>null,
  persionMaxLimit: 0,
  all: <number | null>null,
  allLimit: 0
});

const collapse = ref([]);

let timer: any;

const gamesActionSelect = ref();

const activeGameIndex = ref(0);
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const games = computed(() => {
  let list = cloneDeep(gameTotal.value);
  list.sort((a, b) => a.LotterySort - b.LotterySort);
  return list;
});
const gamesActions = computed(() => {
  return games.value.map((v, i) => ({ text: v.Name, value: i }));
});

const currentData = computed(() => {
  return games.value[activeGameIndex.value];
});

// 获取消息
const getData = async (item: GameLeftMo) => {
  try {
    state.loading = true;
    const res = await reqGameOddsShow(item.LotteryId);
    state.list = cloneDeep(Object.values(res.data));
    state.defaultList = cloneDeep(Object.values(res.data));
    state.minLimit = Math.max(...state.list.map(item => item.MinPersonl));
    state.maxLimit = Math.max(...state.list.map(item => item.MaxMaxPreBet));
    state.persionMaxLimit = Math.max(...state.list.map(item => item.MaxMaxSingleBitch));
    state.allLimit = Math.max(...state.list.map(item => item.MaxMaxBitch));
    state.loading = false;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

watch(
  () => activeGameIndex.value,
  () => {
    nextTick(() => {
      getData(currentData.value);
    });
  }
);

onMounted(() => {
  getData(currentData.value);
});
onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});

// 比较原始数据和修改后的数据，找出有变化的对象
const getChangedItems = (original: OddsSettingItem[], modified: OddsSettingItem[]) => {
  const changedItems: OddsSettingItem[] = [];

  original.forEach((originalItem, index) => {
    const modifiedItem = modified[index];

    // 对比每个字段，如果字段发生变化，记录这个对象
    if (!isEqual(originalItem, modifiedItem)) {
      changedItems.push(modifiedItem); // 保存修改后的数据
    }
  });

  return changedItems;
};

// 保存修改的全部
const handleSaveAll = (flag: boolean = false) => {
  if (!premsStore.isEditOddsSetting) {
    toast.info("暂无权限");
    return;
  }
  showConfirmDialog({
    title: "",
    message: "是否进行【全部修改】操作",
    className: "confirm-dialog",
    beforeClose: async (action: string) => {
      return new Promise<boolean>(async resolve => {
        if (action === "confirm") {
          const loading = toast.loading("修改中...");

          try {
            const list = getChangedItems(state.defaultList, state.list);
            var newList = cloneDeep(list);
            newList.forEach(modifiedItem => {
              modifiedItem.MaxLimitPersonBet = Number(modifiedItem.MaxLimitPersonBet);
              modifiedItem.MaxMaxBitch = Number(modifiedItem.MaxMaxBitch);
              modifiedItem.MaxMaxPreBet = Number(modifiedItem.MaxMaxPreBet);
              modifiedItem.MaxMaxSingleBitch = Number(modifiedItem.MaxMaxSingleBitch);
              modifiedItem.MaxOdds = Number(modifiedItem.MaxOdds);
              modifiedItem.MinPersonl = Number(modifiedItem.MinPersonl);
              modifiedItem.Odds = Number(modifiedItem.Odds);
              modifiedItem.Odds2 = Number(modifiedItem.Odds2);
              modifiedItem.RoomAllLimit = Number(modifiedItem.RoomAllLimit);
              modifiedItem.RoomOdds = Number(modifiedItem.RoomOdds);
              modifiedItem.RoomOdds2 = Number(modifiedItem.RoomOdds2);
              modifiedItem.RoomSingleMaxLimit = Number(modifiedItem.RoomSingleMaxLimit);
              modifiedItem.RoomSingleMinLimit = Number(modifiedItem.RoomSingleMinLimit);
            });
            console.log(newList);
            await reqGameOddsEdit({
              ...(flag ? { ChangeSameCategory: 1 } : {}),
              LotteryId: currentData.value?.LotteryId,
              List: flag ? [] : newList
            });
            loading.close();
            toast.success("修改成功");
            state.all = null;
            state.min = null;
            state.max = null;
            state.persionMax = null;
            getData(currentData.value!);
            resolve(true);
          } catch (error) {
            resolve(true);
          }
          resolve(true);
          // try {

          // 	const list = getChangedItems(state.defaultList, state.list);
          // 	await reqGameOddsEdit({
          // 		...(flag ? { ChangeSameCategory: 1 } : {}),
          // 		LotteryId: currentData.value?.LotteryId,
          // 		List: flag ? [] : list
          // 	});
          // 	toast.success("修改成功");

          // 	state.all = null;
          // 	state.min = null;
          // 	state.max = null;
          // 	state.persionMax = null;
          // 	loading.close();
          // 	getData();
          // 	resolve(true);
          // } catch (error) {
          // 	// toast.fail("修改成功");
          // 	loading.close();
          // 	resolve(true);
          // }
        } else {
          resolve(true);
        }
      });
    }
  });
};
</script>

<style scoped lang="scss">
.c-action-select {
  & > :deep(div) {
    &:first-child {
      width: auto;

      .mr-\[12px\] {
        margin-right: 7px;
      }
    }
  }
}
</style>
